﻿using System;
using System.Collections.Specialized;
using System.Linq;
using System.Security.Principal;
using System.Web;
using EPiServer.Personalization.VisitorGroups;

namespace CriteriaPack.SelectedLanguageCriterion
{
    [VisitorGroupCriterion(
        Category = "Site Criteria",
        Description = "Inspects the language that the user is viewing a page in when using fallbacks",
        DisplayName = "Selected Language")]
    public class SelectedLanguageCriterion : CriterionBase<SelectedLanguageModel>
    {
        public override bool IsMatch(IPrincipal principal, HttpContextBase httpContext)
        {
            NameValueCollection queryStringKeys = httpContext.Request.QueryString;

            if (queryStringKeys.AllKeys.Contains("epslanguage"))
            {
                switch (Model.Condition)
                {
                    case SelectedLanguageCondition.IsViewingIn:
                        return queryStringKeys["epslanguage"].Equals(Model.SelectedLanguage, StringComparison.CurrentCultureIgnoreCase);

                    case SelectedLanguageCondition.IsNotViewingIn:
                        return !queryStringKeys["epslanguage"].Equals(Model.SelectedLanguage, StringComparison.CurrentCultureIgnoreCase);

                    default:
                        return false;
                }
            }
            else
            {
                return false;
            }
        }
    }
}